package com.michaelbulava.TFS.tasks.vc;

import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.tasks.BackgroundableTask;
import com.michaelbulava.TFS.vcs.TFSVcs;
import com.michaelbulava.TFS.vcs.exceptions.TFSException;
import com.michaelbulava.TFS.vcs.internal.SharedOperations;
import com.michaelbulava.TFS.vcs.internal.WorkstationHelper;
import com.michaelbulava.TFS.vcs.utils.TFSFileUtil;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by MichaelA on 11/16/2015.
 */
public class UndoPendingChangesTask extends BackgroundableTask {

    private final List<FilePath> myFiles;

    public UndoPendingChangesTask(Project project, VirtualFile[] files) {
        this(project, TFSFileUtil.getFilePaths(files));
    }

    public UndoPendingChangesTask(Project project, @NotNull List<FilePath> files){
        super(project, Messages.getString("UndoPendingChangesTask.Title"), false);
        myFiles = files;
    }

    @Override
    protected boolean runInBackground() {
        return false;
    }

    @Override
    public void run(final ProgressIndicator indicator) {
        final List<VcsException> errors = new ArrayList<VcsException>();
        try {
            WorkstationHelper.processByWorkspaces(myFiles, true, myProject, indicator,
                    new WorkstationHelper.VoidDelegateProcess() {
                        @Override
                        public void executeRequest(Workspace workspace, List<FilePath> localPaths) throws TFSException {
                             errors.addAll(SharedOperations.performUndo(myProject, workspace, localPaths, indicator));
                        }
                    });
        } catch (TFSException e) {
            errors.add(new VcsException(e));
        }
        if (!errors.isEmpty()){
            AbstractVcsHelper.getInstance(myProject).showErrors(errors, TFSVcs.VCS_NAME);
        } else{
            //TODO show a ballon to indicate that we completed the undo?
        }
    }
}
